package the.guanzhong.express.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.wisteria.framework.util.DateUtils;
import the.broccoli.uc.constant.UserTypeEnum;
import the.broccoli.uc.entity.User;
import the.broccoli.uc.service.IUserService;
import the.broccoli.weixin.configuration.WistWeiXinProperties;
import the.broccoli.weixin.service.dto.WeiXinMpSubscribeDTO;
import the.broccoli.weixin.service.support.MpSubscribeService;
import the.guanzhong.express.service.dto.OrderStatusUpdateMessageDTO;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 微信公众号服务类
 */
@Service
@Slf4j
public class ExpressMpService implements MpSubscribeService {

    @Resource
    private IUserService userService;

    @Resource
    private WxMpService wxMpService;

    private Integer tenantId = 300006;

    @Resource
    private WistWeiXinProperties wistWeiXinProperties;

    /**
     * 关注公众号事件
     * @param dto   关注信息
     */
    @Override
    public void subscribe(WeiXinMpSubscribeDTO dto) {
        if (!StringUtils.hasText(dto.getUnionId()) || !StringUtils.hasText(dto.getOpenId())) {
            return;
        }

        User unionUser = userService.getByUnionId(dto.getUnionId());
        if (unionUser == null) {
            User user = new User();
            user.setCreatedTime(new Date());
            user.setModifiedTime(new Date());
            user.setTenantId(tenantId);
            user.setUserType(UserTypeEnum.WEIXIN_MP.getCode() + "");
            user.setMpOpenId(dto.getOpenId());
            user.setUnionId(dto.getUnionId());
            userService.save(user);
        } else {
            userService.update(null, new LambdaUpdateWrapper<User>()
                    .set(User::getModifiedTime, new Date())
                    .set(User::getMpOpenId, dto.getOpenId())
                    .eq(User::getUserId, unionUser.getUserId())
            );
        }
    }

    /**
     * 取消关注事件
     * @param dto   取消关注信息
     */
    @Override
    public void unsubscribe(WeiXinMpSubscribeDTO dto) {
        if (!StringUtils.hasText(dto.getUnionId())) {
            return;
        }

        userService.update(null, new LambdaUpdateWrapper<User>()
                .set(User::getModifiedTime, new Date())
                .set(User::getMpOpenId, null)
                .eq(User::getUnionId, dto.getUnionId())
        );
    }

    private static final String TEMPLATE_FRONT_COLOR = "#32CD32";

    /**
     * 确认接单消息通知
     * @param dto   通知信息
     */
    public void notifyOrderStatusUpdate(OrderStatusUpdateMessageDTO dto) {
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder().build();
        templateMessage.setToUser(dto.getMpOpenId());
        templateMessage.setTemplateId("yO9w6FDquUe-9BwOzMGRk1-39ezyZ9SAvlC64AhX-tA");
        templateMessage.setMiniProgram(getMiniProgram());
        WxMpTemplateData firstData = new WxMpTemplateData("first", "您的订单已确认接单。", TEMPLATE_FRONT_COLOR);
        WxMpTemplateData orderMoneySumData = new WxMpTemplateData("keyword1", dto.getToAddress(), TEMPLATE_FRONT_COLOR);
        WxMpTemplateData orderProductNameData = new WxMpTemplateData("keyword2", dto.getOrderStatusName(), TEMPLATE_FRONT_COLOR);
        WxMpTemplateData orderTIme = new WxMpTemplateData("keyword3", DateUtils.formatTime(dto.getReceivingTime()), TEMPLATE_FRONT_COLOR);
        WxMpTemplateData remarkData = new WxMpTemplateData("remark.DATA", dto.getRemark(), TEMPLATE_FRONT_COLOR);
        templateMessage.addData(firstData)
                .addData(orderMoneySumData)
                .addData(orderProductNameData)
                .addData(orderTIme);
        templateMessage.addData(remarkData);
        try {
            String s = wxMpService.getTemplateMsgService()
                    .sendTemplateMsg(templateMessage);
            log.info(s);
        } catch (WxErrorException e) {
            log.error(e.getMessage());
        }
    }

    private WxMpTemplateMessage.MiniProgram getMiniProgram() {
        WxMpTemplateMessage.MiniProgram miniProgram = new WxMpTemplateMessage.MiniProgram();
        miniProgram.setAppid(wistWeiXinProperties.getMiniappAppid());
        miniProgram.setPagePath("/pages/order/order?tabIndex=2");
        return miniProgram;
    }

}
